package cn.lixu.controller;

import cn.lixu.domain.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author LiXu
 * @date 2022/08/18 0018 18:57:14
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * @author lixu
     * @data 2022/08/19 0019 11:34:58
     * @param: null
     * @return: null
     * 提供一个根据Id返回User对象的接口，给order服务调用
     **/
    @GetMapping("/getById/{id}")
    // 标记方法熔断，fallbackMethod指定的是托底方法名称，当远程服务调用出现异常，或是方法本身出现异常，会触发托底方法
    @HystrixCommand(fallbackMethod = "getByIdFallbackMethod")
    public User getById(@PathVariable("id") Long id) {
        String url = "http://user-server/user/getById/" + id;
        User object = restTemplate.getForObject(url, User.class);
        return object;
    }

    /**
     * @author lixu
     * @data 2022/08/19 0019 11:38:38
     * @param: null
     * @return: null
     * 负载均衡算法---随机算法
     **/
    @Bean
    public RandomRule randomRule() {
        return new RandomRule();
    }

    /**
     * @author lixu
     * @data 2022/08/19 0019 16:51:11
     * @param: null
     * @return: null
     * Ribbon使用Hystrix
     **/
    public User getByIdFallbackMethod(@PathVariable("id") Long id) {
        return new User(-1L, "你已经被熔断了", "这是ribbon整合Hystrix的兜底数据");
    }
}
